//help from http://developer.android.com/resources/samples/LunarLander/src/com/example/android/lunarlander/LunarView.html

package edu.cs.cs160.storytime;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import android.os.SystemClock;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class StoryTimeBook extends Activity {
    /** Called when the activity is first created. */
	private Bitmap left_top;
	private Bitmap left_bottom;
	private Bitmap right_top;
	private Bitmap right_bottom;
	private Rect coverRect;
	private Rect leftRect;
	private Rect rightRect;
	private Rect leftRectAnim;
	private Rect rightRectAnim;
	private Rect leftRectBottom;
	private Rect rightRectBottom;
	
	private int animStatusNext = 0;
	private int animStatusPrev = 0;
	
	private long animStart = 0;
	private long animDuration = 2400;

	private boolean animNext = false;
	private boolean animPrev = false;
	
    private float lineStartX;
    private float lineStartY;
    private float lineStopX;
    private float lineStopY;	

    private float lineStartX_center;
    private float lineStartY_center;
    private float lineStopX_center;
    private float lineStopY_center;
    
    int frameLeft; 
    int frameTop;
    int frameRight;
    int frameBottom;
    int frameCenter;    
    
	private TextView displayText;
	
	private ArrayList<ActivatedHotspot> activatedHotspots = new ArrayList<ActivatedHotspot>();
	
	private class ActivatedHotspot {
		public StoryHotspot hotspot;
		public Rect rect;
		public ActivatedHotspot(StoryHotspot hotspot,Rect rect) {
			this.hotspot = hotspot;
			this.rect = rect;
		}
	}
	
	private static final int IMAGE_MAX_SIZE = 16000;
	//private static final int IMAGE_MAX_SIZE = 32;
	
	private StoryBook myBook;
	private int currentPage;
	private boolean coverOpen;
	
	private int rightPageTopResource;
	private int leftPageTopResource;
	private int rightPageBottomResource;
	private int leftPageBottomResource;
	
	private FrameLayout bookLayout;
	private RelativeLayout bookButtonLayout;
	private BookView bookView;
	
	private DisplayMetrics myMetrics;
	
	private boolean mRefresh;
	
	
	MediaPlayer mp;
	
	private void loadBook(int bookID) {
		
//		mp = MediaPlayer.create(this, R.raw.m);
		
		myBook = StoryTime.library.getBook(bookID);
		Log.i("book","name:" + myBook.getName());
		
		Bitmap b = null;
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        b = BitmapFactory.decodeResource(getResources(), myBook.getCover(),o);
		
        myBook.setDimensions(o.outHeight, o.outWidth);
        Log.i("dimensions","height:"+o.outHeight+" bookheight"+myBook.getPageHeight());
		b = null;
	}
	
	//set location to screen center with only cover showing
	private void resetCover() {
		mRefresh = true;
		coverOpen = false;
		myBook.setCurPage(0);
		ImageButton prevButton = ((ImageButton) findViewById(R.id.ButtonPrevious));
		prevButton.setVisibility(View.INVISIBLE);
		Log.i("reset","resetcover");
		return;	
	}
	
	//open cover while sliding book into correct position, to first page
	private void openCover() {
		coverOpen = true;
		ImageButton prevButton = ((ImageButton) findViewById(R.id.ButtonPrevious));
		prevButton.setVisibility(View.VISIBLE);
		return;
	}
	
	//from any page, close cover, animate to center
	private void closeCover() {
		resetCover();
		return;
	}
	
	//turn pages right to left, replacing rightpage with page+2 and leftpage with page+1
	private void nextPage() {
		Log.i("NAVSTATUS","navstatus:"+myBook.navigationStatus());
		//ImageButton nextButton = ((ImageButton) findViewById(R.id.ButtonNext));
		//nextButton.setVisibility(View.INVISIBLE);

		if (!coverOpen) {
			openCover();
		} else if (myBook.navigationStatus() == 1) {
			//closeCover();
			finish();
		} else {
			if (animNext == false) {
				animNext = true;
				animStart = SystemClock.uptimeMillis();
			}
		}
	}
	
	private void previousPage() {
		if (myBook.navigationStatus() == -1) {
			closeCover();
		} else {
			if (animPrev == false) {
				animPrev = true;
				animStart = SystemClock.uptimeMillis();
			}
		}
	}
	
	private void highlightHotspot(StoryHotspot hs,Rect hotspotRect) {
		Log.i("hotspot","highlighting hotspot"+hs.getName()+" "+hotspotRect);
		activatedHotspots.add(new ActivatedHotspot(hs,hotspotRect));	
	}
	
	private void activateHotspot(StoryHotspot hs,Rect hotspotRect) {
		Log.i("hotspot","activating hotspot"+hs.getName()+" "+hotspotRect);
		displayText.setText(hs.getResource(0).getText());
		highlightHotspot(hs,hotspotRect);	
		
		/*
		if (hs.getResource(0).getSound() != -1) {
			mp = MediaPlayer.create(this, hs.getResource(0).getSound());
			if (mp.isPlaying())
				mp.stop();
			mp.seekTo(0);
			mp.start();
		}
		*/
	}
	
	//decodeBitmap from http://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966	
	private Bitmap decodeResourceScaled(int resource){
	    Bitmap b = null;
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        b = BitmapFactory.decodeResource(getResources(), resource,o);
        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        b = BitmapFactory.decodeResource(getResources(), resource,o2);
	    return b;
	}
	
	private void initDisplay() {
	       //layout
        //getwidth of display
        int displayWidth = myMetrics.widthPixels;
        
        //get heightofdisplay
        int displayHeight = myMetrics.heightPixels;
        //get width of picture
        int pictureHeight = myBook.getPageHeight();
        //get height of picture
        int pictureWidth = myBook.getPageWidth();
        
        double displayRatio = (double)displayWidth/(double)displayHeight;
        double pageRatio = (double)pictureWidth*2/(double)pictureHeight;
        //determine greater ratio (width/width or height/height)
        int pageViewWidth = 0;
        int pageViewHeight = 0;
        int verticalSpacing = 0;
        int horizontalSpacing = 0;
        double sizeRatio = 1;
        if (displayRatio < pageRatio) {
        	sizeRatio = (double) (pictureWidth*2)/(double) displayWidth;
         	pageViewHeight = (int) Math.floor((double)pictureHeight / sizeRatio);
        	pageViewWidth = (int) Math.floor((double)pictureWidth / sizeRatio);
        	verticalSpacing = (int) (((double) displayHeight - (double)pageViewHeight)/2);
        } else if (displayRatio > pageRatio) {
        	sizeRatio = (double) pictureHeight/(double) displayHeight;
        	pageViewHeight = (int) Math.floor((double)pictureHeight / sizeRatio);
        	pageViewWidth = (int) Math.floor((double)pictureWidth/sizeRatio);
        	horizontalSpacing = (int) ((double)displayWidth - (double)pageViewWidth*2.0)/2;	
        } else {
        	pageViewHeight = pictureHeight;
        	pageViewWidth = pictureWidth;
        }
        
        frameLeft = 0+horizontalSpacing; 
        frameTop = 0+verticalSpacing;
        frameRight = myMetrics.widthPixels-horizontalSpacing;
        frameBottom = myMetrics.heightPixels-verticalSpacing;
        frameCenter = (frameRight + frameLeft) / 2;
        int buttonWidth = 80;
        
        
        RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(buttonWidth,buttonWidth);
        //layoutParams1.setMargins(horizontalSpacing+1,verticalSpacing,horizontalSpacing,verticalSpacing);
        layoutParams1.setMargins(1,1,horizontalSpacing,verticalSpacing);
        ((ImageButton) findViewById(R.id.ButtonLibrary)).setLayoutParams(layoutParams1);
        RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(buttonWidth,buttonWidth);
        layoutParams2.setMargins(frameRight-buttonWidth-1,verticalSpacing,horizontalSpacing,verticalSpacing);
        ((ImageButton) findViewById(R.id.ButtonLock)).setLayoutParams(layoutParams2);
        RelativeLayout.LayoutParams layoutParams3 = new RelativeLayout.LayoutParams(buttonWidth,buttonWidth);
        //layoutParams3.setMargins(frameRight-buttonWidth-1,frameBottom-buttonWidth,horizontalSpacing,verticalSpacing);
        layoutParams3.setMargins(myMetrics.widthPixels-buttonWidth-1,myMetrics.heightPixels-buttonWidth,0,0);
        ((ImageButton) findViewById(R.id.ButtonNext)).setLayoutParams(layoutParams3);
        RelativeLayout.LayoutParams layoutParams4 = new RelativeLayout.LayoutParams(buttonWidth,buttonWidth);
        //layoutParams4.setMargins(horizontalSpacing+1,frameBottom-buttonWidth,horizontalSpacing,verticalSpacing);
        layoutParams4.setMargins(1,myMetrics.heightPixels-buttonWidth,0,0);
        ((ImageButton) findViewById(R.id.ButtonPrevious)).setLayoutParams(layoutParams4);
		
        ImageButton lockButton = ((ImageButton) findViewById(R.id.ButtonLock));
		lockButton.setVisibility(View.INVISIBLE);		
        
        leftRect = new Rect(frameLeft, frameTop, frameCenter, frameBottom);
        //rightRect = new Rect(frameCenter, frameTop, (frameRight - frameCenter)/2+frameCenter, frameBottom);
        rightRect = new Rect(frameCenter, frameTop, frameRight, frameBottom);
        leftRectBottom = new Rect(frameLeft, frameTop, frameCenter, frameBottom);
        rightRectBottom = new Rect(frameCenter, frameTop, frameRight, frameBottom);

        leftRectAnim = new Rect(frameLeft, frameTop, frameCenter, frameBottom);
        //rightRect = new Rect(frameCenter, frameTop, (frameRight - frameCenter)/2+frameCenter, frameBottom);
        rightRectAnim = new Rect(frameCenter, frameTop, frameRight, frameBottom);
        
        lineStartX =(frameRight - frameCenter)/2+frameCenter;
        lineStartY = frameTop;
        lineStopX = lineStartX + 1;
        lineStopY = frameBottom;
        
        lineStartX_center = frameCenter;
        lineStartY_center = frameTop;
        lineStopX_center = lineStartX_center + 1;
        lineStopY_center = frameBottom;
        
        Log.i("coords ","frameright:"+frameRight+" frameLeft:"+frameLeft+" frameTop:"+frameTop+" frameBottom:"+frameBottom+" frameCenter:"+frameCenter);
        Log.i("images","images:"+bookLayout.getRight()+" "+bookLayout.getBottom());
		Log.i("spacing info", "spacings:" + " hs:" + 
				horizontalSpacing + " vs:" + 
				verticalSpacing + " dw:" + 
				displayWidth + " dh:" +
				displayHeight + " pw:" +
				pictureWidth + " ph:" +
				pictureHeight + " dr:" +
				displayRatio + " pr:" +
				pageRatio + " pvh:" +
				pageViewHeight + " pvw:" +
				pageViewWidth + "sizeratio" +
				sizeRatio
		);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        
        setContentView(R.layout.book);
        mRefresh = false;
        myMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(myMetrics);
        
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "test");

		bookView = new BookView(this);
		displayText = (TextView) findViewById(R.id.DisplayText);
		bookLayout = ((FrameLayout) findViewById(R.id.booklayout));
        bookButtonLayout = ((RelativeLayout) findViewById(R.id.bookbuttonlayout));
        
		bookLayout.addView(bookView);        
		loadBook(StoryTime.library.getSelectedID());
		initDisplay();
		resetCover();
		
        ImageButton lib = (ImageButton) findViewById(R.id.ButtonLibrary);
        lib.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	finish();
            }

        });
        ImageButton next = (ImageButton) findViewById(R.id.ButtonNext);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Log.i("Navigation","GO FORWARD");
            	nextPage();
            }

        });
        ImageButton prev = (ImageButton) findViewById(R.id.ButtonPrevious);
        prev.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Log.i("Navigation","GO BACK");
            	previousPage();
            }

        });
        
    }
    
    @Override
    protected void onDestroy() {
		
    	super.onDestroy();
    	setResult(StoryTime.LOAD_LIBRARY_ON_EXIT);
    	Log.i("ending","ending book");
    }
    
    public class BookView extends SurfaceView implements SurfaceHolder.Callback {
    	class BookThread extends Thread {
    		private Handler mHandler;
    		private SurfaceHolder mSurfaceHolder;
    		private boolean mRun = true;
    		public Paint p;
    		public BookThread(SurfaceHolder surfaceHolder, Context context,
                    Handler handler) {
    			mSurfaceHolder = surfaceHolder;
                mHandler = handler;
                mContext = context;
                p = new Paint();
                p.setColor(Color.BLACK);
    		}
    		
            public void setRunning(boolean b) {
                mRun = b;
            }
            
            @Override
            public void run() {
                while (mRun) {
                    Canvas c = null;
                    doPages();
                    try {
                        c = mSurfaceHolder.lockCanvas(null);
                        synchronized (mSurfaceHolder) {
                        	
                            doDraw(c);
                        }
                    } finally {
                        // do this in a finally so that if an exception is thrown
                        // during the above, we don't leave the Surface in an
                        // inconsistent state
                        if (c != null) {
                            mSurfaceHolder.unlockCanvasAndPost(c);
                        }
                    }
                }
            } 
            
            private void doPages() {
            	if (animPrev == true) {
    				if (animStatusPrev < animDuration) {
    					animStatusPrev = animStatusPrev+ ((int)(SystemClock.uptimeMillis() - animStart));;
    				} else { 
    					
    					animPrev = false;
    					myBook.prevPage();
    					animStatusPrev = 0;
    				}
    			}    
    			if (animNext == true) {
    				if (animStatusNext < animDuration) {
    					animStatusNext = animStatusNext + ((int)(SystemClock.uptimeMillis() - animStart));
    				} else { 
    					
    					animNext = false;
    					myBook.nextPage();
    					animStatusNext = 0;
    				}
    			}
    			Log.i("animstatus","animnext"+animStatusNext+ " animprev"+animStatusPrev);
            }
            
            private void doDraw(Canvas canvas) {
            	//Log.i("dodraw","dodraw");
            	if (coverOpen) {
            		left_bottom = decodeResourceScaled(myBook.getCurPageOffset(-1).returnPageResource());
            		left_top = decodeResourceScaled(myBook.getCurPageOffset(0).returnPageResource());
	            	right_top = decodeResourceScaled(myBook.getCurPageOffset(1).returnPageResource());
	            	right_bottom = decodeResourceScaled(myBook.getCurPageOffset(2).returnPageResource());
	            	//left_bottom = BitmapFactory.decodeResource(getResources(), myBook.getCurPageOffset(-1).returnPageResource(),bfo);
            		//left_top = BitmapFactory.decodeResource(getResources(), myBook.getCurPageOffset(0).returnPageResource(),bfo);
	            	//right_top = BitmapFactory.decodeResource(getResources(), myBook.getCurPageOffset(1).returnPageResource(),bfo);
	            	//right_bottom = BitmapFactory.decodeResource(getResources(), myBook.getCurPageOffset(2).returnPageResource(),bfo);
	            	
	            	float animProgress = 0;
	            	
	            	
	            	if (animNext == true) {
	            		left_bottom = decodeResourceScaled(myBook.getCurPageOffset(0).returnPageResource());
	            		left_top = decodeResourceScaled(myBook.getCurPageOffset(2).returnPageResource());
		            	right_top = decodeResourceScaled(myBook.getCurPageOffset(1).returnPageResource());
		            	right_bottom = decodeResourceScaled(myBook.getCurPageOffset(3).returnPageResource());
	            		animProgress = (float) Math.min(((float)animStatusNext/(float)animDuration),1.0);
	            		Log.i("animProgress","animPos"+(int)((frameCenter - frameLeft)*(animProgress-0.5)*2+frameLeft)+"fl"+frameLeft);
	            		if (animProgress > 0.5) {
		            		leftRectAnim = new Rect((int)((frameCenter - frameLeft)*(1-((animProgress-0.5)*2))+frameLeft), frameTop, frameCenter, frameBottom);
			                rightRectAnim = new Rect(frameCenter, frameTop, frameCenter, frameBottom);
	            		} else {
	            			leftRectAnim = new Rect(frameCenter, frameTop, frameCenter, frameBottom);
			                rightRectAnim = new Rect(frameCenter, frameTop, (int)((frameRight - frameCenter)*(1-animProgress*2)+frameCenter), frameBottom);
	            		}
	            	} else if (animPrev == true) {
	            		left_bottom = decodeResourceScaled(myBook.getCurPageOffset(-2).returnPageResource());
	            		left_top = decodeResourceScaled(myBook.getCurPageOffset(0).returnPageResource());
		            	right_top = decodeResourceScaled(myBook.getCurPageOffset(-1).returnPageResource());
		            	right_bottom = decodeResourceScaled(myBook.getCurPageOffset(1).returnPageResource());
	            		animProgress = (float) Math.min(((float)animStatusPrev/(float)animDuration),1.0);
	            		if (animProgress < 0.5) {
		            		leftRectAnim = new Rect((int)((frameCenter - frameLeft)*(animProgress)*2+frameLeft), frameTop, frameCenter, frameBottom);
			                rightRectAnim = new Rect(frameCenter, frameTop, frameCenter, frameBottom);
	            		} else {
	            			leftRectAnim = new Rect(frameCenter, frameTop, frameCenter, frameBottom);
			                rightRectAnim = new Rect(frameCenter, frameTop, (int)((frameRight - frameCenter)*((animProgress-0.5)*2)+frameCenter), frameBottom);
	            		}
	            	} else {
	            		left_bottom = decodeResourceScaled(myBook.getCurPageOffset(-1).returnPageResource());
	            		left_top = decodeResourceScaled(myBook.getCurPageOffset(0).returnPageResource());
		            	right_top = decodeResourceScaled(myBook.getCurPageOffset(1).returnPageResource());
		            	right_bottom = decodeResourceScaled(myBook.getCurPageOffset(2).returnPageResource());
	            		leftRectAnim = leftRect;
	            		rightRectAnim = rightRect;
	            	}
	            	Log.i("animProgress","animProgress"+animProgress+animNext+animPrev);
	                //rightRectAnim = new Rect(frameCenter, frameTop, frameRight, frameBottom);
	                
	            	if (left_bottom != null) {
	            		canvas.drawBitmap(left_bottom, null,leftRectBottom, p);
	            		left_bottom.recycle();
	            		left_bottom = null;
	            	}
	            	if (right_bottom != null) {
	            		canvas.drawBitmap(right_bottom, null,rightRectBottom, p);
	            		right_bottom.recycle();
	            		right_bottom = null;
	            	}
	            	if (left_top != null) {
	            		canvas.drawBitmap(left_top, null,leftRectAnim, p);
	            		left_top.recycle();
	            		left_top = null;
	            	}
	            	if (right_top != null) {
	            		canvas.drawBitmap(right_top, null,rightRectAnim, p);
	            		//canvas.drawLine(lineStartX,lineStartY,lineStopX,lineStopY,p);
	            		right_top.recycle();
	            		right_top = null;
	            	}
	            	
	            	canvas.drawLine(lineStartX_center,lineStartY_center,lineStopX_center,lineStopY_center,p);
	            	
	            	//drawHotspots
	            	Bitmap hotspotBitmap = decodeResourceScaled(R.drawable.hotspothighlight); 
	         		
	            	Iterator<ActivatedHotspot> itr = activatedHotspots.iterator();
	            	Log.i("hotspots","hotspots");
	            	while (itr.hasNext()){
	    			   ActivatedHotspot nextHS = itr.next();
	    			   Log.i("hotspots","activating hotspots"+nextHS);
	    			   canvas.drawBitmap(hotspotBitmap, null,nextHS.rect, p);
	            	}
	            	
	            	
            	} else {
            		left_top = null;
            		
            		right_top = decodeResourceScaled(myBook.getCover());
            		right_bottom = decodeResourceScaled(myBook.getPage(0).returnPageResource());
	            	canvas.drawBitmap(right_bottom, null, rightRect, p);
            		canvas.drawBitmap(right_top, null, rightRect, p);
            		canvas.drawRect(leftRect, p);
	            	right_top.recycle();
	            	right_top = null;
            	}
            	Log.i("time:","time: "+SystemClock.uptimeMillis());
            }
    	}
    	
    	@Override
    	public boolean onTouchEvent(MotionEvent event) {
    		Log.i("touch","touch "+event.getX()+" "+event.getY());
    		if(event.getAction() == MotionEvent.ACTION_DOWN)
    		{
    			Rect tempRect = null;
    			Rect hotspotRect = null;
    			Rect activatedHotspotRect = null;
    			StoryPage tempPage = null;
    			StoryHotspot nextHS = null;
    			StoryHotspot activatedHotspot = null;
    			Iterator<StoryHotspot> itr;
    			boolean foundRect = false;
    			int xCoord = (int) event.getX();
    			int yCoord = (int) event.getY();
    			if (leftRect.contains(xCoord,yCoord)) {
    				tempRect = leftRect;
    				tempPage = myBook.getCurPageOffset(0);
    				Log.i("touch","leftrect contains "+event.getX()+" "+event.getY());
    				foundRect = true;
    			} else if (rightRect.contains(xCoord,yCoord)) {
    				tempRect = rightRect;
    				tempPage = myBook.getCurPageOffset(1);
    				Log.i("touch","rightrect contains "+event.getX()+" "+event.getY());
    				foundRect = true;
    			}
    			if (foundRect) {
    				boolean foundHotspot = false;
    				Log.i("touch","foundrect"+tempPage.getHotspots().size());
    			    itr = tempPage.getHotspots().iterator();
    			    while (itr.hasNext()){
    			      nextHS = itr.next();
    			      hotspotRect = new Rect(
    			    		  tempRect.left+(int)(tempRect.width()*nextHS.getLeft()),
    			    		  
    			    		  tempRect.top+(int)(tempRect.width()*nextHS.getTop()),
    			    		  tempRect.left+(int)(tempRect.width()*nextHS.getRight()),
    			    		  tempRect.top+(int)(tempRect.width()*nextHS.getBottom()));
    			      Log.i("touch","hotspot test "+hotspotRect);
    			    	if (hotspotRect.contains(xCoord,yCoord)) {
    			    		Log.i("touch","hotspot contains "+hotspotRect);
    			    		if (activatedHotspotRect == null || (activatedHotspotRect != null && activatedHotspotRect.contains(hotspotRect))) {
			    				foundHotspot = true;
			    				activatedHotspot = nextHS;
			    				activatedHotspotRect = hotspotRect;
			    				break;
    			    		}
    			    	}
    			    }
    			    if (foundHotspot) {
    			    	activateHotspot(activatedHotspot,activatedHotspotRect);
    			    } else {
    			    	itr = tempPage.getHotspots().iterator();
        			    while (itr.hasNext()){
        			    	nextHS = itr.next();
        			    	hotspotRect = new Rect(
          			    		  tempRect.left+(int)(tempRect.width()*nextHS.getLeft()),
          			    		 tempRect.top+(int)(tempRect.width()*nextHS.getTop()),
          			    		  tempRect.left+(int)(tempRect.width()*nextHS.getRight()),
          			    		 
          			    		  tempRect.top+(int)(tempRect.width()*nextHS.getBottom()));
        			    	highlightHotspot(nextHS,hotspotRect);
        			    }
    			    }
    			}
    		}
    		if(event.getAction() == MotionEvent.ACTION_UP)
    		{
    			activatedHotspots.clear();
    			displayText.setText("");
    		}
    		return true;
    	}
    	private Context mContext;
    	private BookThread thread;
    	
		public BookView(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
	        SurfaceHolder holder = getHolder();
	        holder.addCallback(this);
			thread = new BookThread(holder, context, new Handler() {
	            public void handleMessage(Message m) {
	            	
	            }
			});
			setFocusable(true);
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub
			
		}

		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
	        thread.start();
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
	        boolean retry = true;
	        thread.setRunning(false);
	        while (retry) {
	            try {
	                thread.join();
	                retry = false;
	            } catch (InterruptedException e) {
	            }
	        }			
		}
    	
    }
}